class Solution:
    def reverse(self, x: int) -> int:
        # 判断正负
        if x < 0:
            sign = -1
        else:
            sign = 1
        # 反转数字
        x = abs(x)
        res = 0
        if sign == 1:
            while x != 0:
                if res > (2**31 - 1) // 10:
                    return 0
                elif res == (2**31 - 1) // 10:
                    return 0 if x % 10 > 7 else sign * (res * 10 + x % 10)
                else:
                    res = res * 10 + x % 10
                x //= 10
            return sign * res
        else:
            while x != 0:
                if res > (2**31) // 10:
                    return 0
                elif res == (2**31) // 10:
                    return 0 if x % 10 > 8 else sign * (res * 10 + x % 10)
                else:
                    res = res * 10 + x % 10
                x //= 10
            return sign * res


x = -123
sol = Solution()
print(sol.reverse(x))
